package org.example.chat.controller;

import org.example.chat.api.CommonResult;
import org.example.chat.entity.ChatMessage;
import org.example.chat.service.IFriendRequestService;
import org.example.chat.service.IUserService;
import org.example.chat.vo.FriendRequestVo;
import org.example.chat.websocket.entity.ChannelContext;
import org.example.chat.websocket.entity.MessagePack;
import org.example.chat.websocket.entity.MessageType;
import org.example.chat.websocket.entity.QueueMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/friendRequest")
public class FriendRequestController extends BaseController {

    @Autowired
    private IFriendRequestService friendRequestService;
    @Autowired
    private ChannelContext channelContext;
    @Autowired
    private IUserService userService;

    @PostMapping("/launch")
    public CommonResult launchRequest(@Validated @RequestBody FriendRequestVo friendRequestVo) {
        // 1. 发起添加请求
        int flag = friendRequestService.addFriendRequest(friendRequestVo);
        if (flag == 1) {
            return CommonResult.fail("已经发起过请求");
        } else if (flag == 2) {
            return CommonResult.fail("已经是好友关系");
        }
        // 2. 发起成功后，服务器主动向被发送者推送请求信息，让被请求者客户端弹出请求提示并主动更新好友请求列表(异步推送)
        executor.execute(new Runnable() {
            @Override
            public void run() {
                MessagePack messagePack = new MessagePack();
                messagePack.setType(MessageType.SYSTEM_NOTIFY.getType());
                ChatMessage chatMessage = new ChatMessage();
                chatMessage.setMessage(getLoginUserInfo().getUser().getNickname() + "请求添加为好友");
                messagePack.setChatMessage(chatMessage);
                channelContext.send(friendRequestVo.getAcceptUserId(), messagePack, QueueMessage.Type.SIGNAL);
            }
        });
        return CommonResult.success("请求已发起，请等待通过");
    }
}
